// index.js
import {request} from "~/utils/request.js"
Page({
  data: {
    check: false,
    address: "",
    options: [],
    longitude:"",
    latitude:"",
    carinfo: {
      carNum: "",
      inputPlates: "",
      isPlate: "",
      isNewEnergy: "",
      address: ""
    },
    "reasonsOptions": [],
    vehicleNumber: "", // 车牌号
    mobile: "", // 手机号
    reason: "",
    name: "",
    driving: false,
    withPartner: false,
    config:{
      "reasons": true, // 进山事由
      "driving": true, // 是否有车
      "partners": true, // 老人小孩
      "name": true, // 姓名
      "mobile": true, // 手机号
      "callNumber": ""
    }
     
  },
  onCarChange () {
    this.setData({
      driving: !this.data.driving
    })
  },
  onChange () {
    this.setData({
      withPartner: !this.data.withPartner
    })
  },
  onChooseReason (e) {
    this.setData({
      reason: e.currentTarget.dataset.reason
    })
  },
  async onLoad () {
    this.onLogin()
  },
  async onLogin () {
    wx.login({
      success: (res) => {
        return request("member/login", { code:res.code }, "post").then(ret =>{
          console.log(ret)
          wx.setStorageSync('token', ret.token)
          this.getConfig()
        })
      },
    })
  },
  onAddressBlur (e) {
    this.setData({
      address: e.detail.value
    })
  },
  onNameBlur (e) {
    this.setData({
      name: e.detail.value
    })
  },
  onSubmit () {
    console.log(this.data)
    if (!this.data.check) return
    let config = this.data.config
    let { 
      longitude, 
      latitude,
      address,
      reason,
      withPartner,
      name,
      mobile,
      carinfo,
      driving
    } = this.data
   
    if (!address) return this.showToast("请填写当前位置")
    if (config.reasons && !reason) return this.showToast("请选择进山事由")
    if (config.name && !name) return this.showToast("请填写联系人")
    if (config.mobile && !mobile) return this.showToast("请填写手机号码")
    if (config.driving && driving && !carinfo.carNum) return this.showToast("请填车牌号")
    let params = {
      withPartner,
      name,
      mobile,
      vehicleNumber: carinfo.carNum,
      address,
      reasons: [reason],
      longitude, 
      latitude,
    }
    wx.requestSubscribeMessage({
      tmplIds: ['eioJFCAbkMYM3fHXr1KuED4VvDpxki2b3utNHJgub_g'],
      success() {
        request("member/visit", params, "post").then(res =>{
          wx.showToast({
            title: "保存成功",
            icon: 'none'
          })
          wx.navigateTo({
            url: '/pages/history/history',
          })
        })
      },
      fail(err) {
        console.log("失败")
      }
    })
  },
  reqMsg () {
    wx.requestSubscribeMessage({
      tmplIds: ['eioJFCAbkMYM3fHXr1KuED4VvDpxki2b3utNHJgub_g'],
      success() {
        
      },
      fail(err) {
        console.log("失败")
      }
    })
  },
  showToast (title) {
    wx.showToast({
      title: title,
      icon: 'none'
    })
  },
  getConfig() {
    console.log(request)
    request("member/config").then(res => {
      console.log(res)
      this.setData({
        config: res
      })
    })
  },
  getPostion() {
    let _this = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude; // 纬度  
        var longitude = res.longitude; // 经度  
        _this.latitude = latitude
        _this.longitude = longitude
        // 调用腾讯地图API获取中文坐标表示  
        wx.request({
          url: 'https://apis.map.qq.com/ws/geocoder/v1/?address=',
          // url: 'https://apis.map.qq.com/ws/coord/v1/?address=',
          method: 'GET',
          data: {
            location: latitude + ',' + longitude,
            key: 'YBTBZ-YKHHZ-5VSXD-ZH77A-BUAPQ-5ZBVG' // 替换为你的QQ地图API密钥  
            // key: 'A4CBZ-MBAWQ-JVV5T-BXZWL-WRJL2-4FF5D' // 冷链替换为你的QQ地图API密钥  
          },
          success: function (res) {
            console.log(res)
            if (res.data && res.data.status === 0) {
              var result = res.data.result;
              var address = result.address; // 地址信息  
              _this.setData({
                'address': address
              })
              console.log(result, address); // 打印地址信息  
            } else {
              console.log(res)
              wx.showToast({
                title: res.data.message || "获取位置失败",
                icon: 'none'
              })
            }
          },
          fail: function () {
            console.log('请求腾讯地图API失败');
          }
        });
      }
    });
  },
  makePhoneCall() {
    const phoneNumber = this.data.config.callNumber; // 替换成要拨打的电话号码
    wx.makePhoneCall({
      phoneNumber: phoneNumber
    })
  },
  sendDemo () {
    request("member/push", {
        templateId: 'eioJFCAbkMYM3fHXr1KuED4VvDpxki2b3utNHJgub_g',
        page: '/pages/detail/detail?id=da515b4b1d0b415798456882adbd5e6d',
        data: [
            {name: 'time2', value: '2020年10月11日 20:15:22'},
            {name: 'thing4', value: '您的上山时限已超时,请及时反馈,点击查看详情'}
        ],
        miniprogramState: 'developer'
    }, 'post')
  },
  getCarNum(e) {
    let carinfo = {}
    carinfo.carNum = e.detail.carNum || ""
    carinfo.inputPlates = e.detail.inputPlates || ""
    carinfo.isPlate = e.detail.isPlate || ""
    carinfo.isNewEnergy = e.detail.isNewEnergy || ""
    console.log('carinfo', carinfo )
    this.setData({
      carinfo
    })
  },
  onGoto() {
    wx.navigateTo({
      url: '/pages/history/history',
    })
  },
  onCheck() {
    this.setData({
      check: !this.data.check
    })
    console.log(this.data.check)
  },
  getPhoneNumber(e) { // 获取手机号
    if (!e.detail.code) return
    request('member/account/mobile?code='+ e.detail.code).then(res =>{
      this.setData({
        mobile: res
      })
    })
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    const {
      nickName
    } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const {
      avatarUrl
    } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },

})